<?php
/**
 * Created by PhpStorm.
 * User: wanglong
 * Date: 2017/12/26
 * Time: 22:14
 */

namespace app\common\services;


class UploadServices extends BaseServices
{
    //根据文件路径进行上传
    public static function uploadByFile($file_name,$file_path,$bucket='')
    {
        if(!$file_name){
            return self::_error("参数文件名时必须的~~");
        }

        if(!$file_path || !file_exists($file_path)){
            return self::_error("请输入合法的文件路径");
        }


        $upload_config=\Yii::$app->params['upload'];
        if(!isset($upload_config[$bucket])){
            return self::_error("指定参数bucket错误");
        }

        //获取文件后缀名
        $tmp_file_extend=explode(".",$file_name);
        $file_type=strtolower(end($tmp_file_extend));
        //文件名
        $hash_key=md5(file_get_contents($file_path));


        //在每个篮子下按照日期放图片
        $upload_dir_path=UtilService::getRootPath()."/web".$upload_config[$bucket]."/";
        //以当前时间设置上传文件的文件夹名
        $folder_name=date("Ymd");
        $upload_dir=$upload_dir_path.$folder_name;


        if(!file_exists($upload_dir)){
            mkdir($upload_dir,0777);
            chmod($upload_dir,0777);
        }

        //最终的上传的整个文件夹名称
        $upload_full_name=$folder_name."/".$hash_key.".{$file_type}";

        //判断如果是通过form表单上传的话使用move_uploaded_file保存图片 否则使用file_put_content函数
        if(is_uploaded_file($file_path)){
            move_uploaded_file($file_path,$upload_dir_path.$upload_full_name);
        }else{
            file_put_contents($upload_dir_path.$upload_full_name,file_get_contents($file_path));
        }

        return [
            'code'=>200,
            'path'=>$upload_full_name,
            'prefix'=>$upload_config[$bucket].'/'
        ];
    }

}